// editor/log/LogManager.java
package org.example.com.editor.logger;

import lombok.Getter;
import org.example.com.editor.command.CommandExecutionListener;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LogManager implements CommandExecutionListener {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    @Getter
    private final Map<String, Boolean> logEnabledMap = new HashMap<>();
    private final Map<String, Boolean> sessionStartedMap = new HashMap<>();

    @Override
    public void onCommandExecuted(String targetFile,String[] args) throws IOException {

        if (targetFile == null || !isLogEnabled(targetFile)) {
            return;
        }


            String logFile = getLogFileName(targetFile);
            ensureSessionStarted(logFile);

            try (FileWriter writer = new FileWriter(logFile, true)) {
                String timestamp = DATE_FORMAT.format(new Date());
                StringBuilder commandLine = new StringBuilder();
                for (String arg : args) {
                    commandLine.append(arg).append(" ");
                }
                writer.write(timestamp + " " + commandLine.toString().trim() + "\n");
            }
    }

    public void enableLog(String filePath) {
        logEnabledMap.put(filePath, true);
    }

    public void disableLog(String filePath) {
        logEnabledMap.put(filePath, false);
    }

    public boolean isLogEnabled(String filePath) {
        return logEnabledMap.getOrDefault(filePath, false);
    }

    public String getLogFileName(String filePath) {
        File file = new File(filePath);
        String parentDir = file.getParent();
        if (parentDir == null) {
            parentDir = System.getProperty("user.dir");
        }
        return parentDir + File.separator + "." + file.getName() + ".log";
    }

    public void showLog(String filePath, ConsoleUI ui) {
        String logFile = getLogFileName(filePath);
        try {
            ui.printInfo("显示日志文件: " + logFile);
            Files.lines(Paths.get(logFile)).forEach(ui::printInfo);
        } catch (IOException e) {
            ui.printError("无法读取日志文件: " + e.getMessage());
        }
    }

    private void ensureSessionStarted(String logFile) throws IOException {
        if (!sessionStartedMap.getOrDefault(logFile, false)) {
            try (FileWriter writer = new FileWriter(logFile, true)) {
                writer.write("session start at " + DATE_FORMAT.format(new Date()) + "\n");
            }
            sessionStartedMap.put(logFile, true);
        }
    }

    public void checkAndEnableLogForFile(String filePath, String firstLine) {
        if (firstLine != null && firstLine.trim().equals("# log")) {
            enableLog(filePath);
        }
    }

}